package likouJava;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的右视图 {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();

        if (root == null)return result;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            int leveSize = queue.size();

            for (int i = 0; i < leveSize; i++) {
                TreeNode node = queue.poll();
                //当前层的最后一个放入结果
                if(i == leveSize - 1){
                    result.add(node.val);
                }

                //将左右子节点加入队列
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return result;
    }

}
